<template>
  <div class="app-container" v-if="canList">
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item"
                placeholder="名字"
                v-model="listQuery.name">
      </el-input>
      <!--<el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item"
                placeholder="性别"
                v-model="listQuery.sex">
      </el-input>-->
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item"
                placeholder="手机号码"
                v-model="listQuery.phone">
      </el-input>
      <!--<el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item"
                placeholder="登录ID"
                v-model="listQuery.openId">
      </el-input>
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item"
                placeholder="统一ID"
                v-model="listQuery.unionId">
      </el-input>
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item"
                placeholder="支付ID"
                v-model="listQuery.payId">
      </el-input>
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item"
                placeholder="左编号"
                v-model="listQuery.treeLeft">
      </el-input>
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item"
                placeholder="右编号"
                v-model="listQuery.treeRight">
      </el-input>
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item"
                placeholder="层次"
                v-model="listQuery.treeLevel">
      </el-input>
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item"
                placeholder="描述"
                v-model="listQuery.info">
      </el-input>-->
      <!--<el-input @keyup.enter.native="handleFilter" style="width: 160px;" class="filter-item"-->
                <!--placeholder="上级ID"-->
                <!--v-model="listQuery.parentId">-->
      <!--</el-input>-->
      <el-select @change='handleFilter'  clearable class="filter-item" style="width: 160px" v-model="listQuery.status"
                 placeholder="状态">
        <el-option v-for="(item,index) in  statusOptions" :key="item" :label="item" :value="index">
        </el-option>
      </el-select>
      <!--<el-date-picker
        v-model="listQuery.joinTime"
        type="datetimerange"
        range-separator="至"
        start-placeholder="加入时间开始"
        end-placeholder="加入时间结束">
      </el-date-picker>-->
      <!--<el-date-picker
        v-model="listQuery.levelTime"
        type="datetimerange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期">
      </el-date-picker>
      <el-date-picker
        v-model="listQuery.loginTime"
        type="datetimerange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期">
      </el-date-picker>-->

      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">查找
      </el-button>
      <!--<el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary"
                 v-if="canSave"     icon="el-icon-edit">添加
      </el-button>-->
      <el-button class="filter-item" type="primary" :loading="downloadLoading" v-waves icon="el-icon-download"
                 @click="handleDownload">导出
      </el-button>
    </div>

    <el-table :key='tableKey' :data="list" v-loading="listLoading" border fit highlight-current-row
              style="width: 100%;min-height:1000px;">
      <el-table-column align="center" width="100px" label="序号">
        <template slot-scope="scope">
          <span>{{scope.row.id}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="130px" label="名字">
        <template slot-scope="scope">
          <span>{{scope.row.name}}</span>
        </template>
      </el-table-column>
      <!--<el-table-column align="center" label="性别">
        <template slot-scope="scope">
          <span>{{scope.row.sex}}</span>
        </template>
      </el-table-column>-->
      <el-table-column align="center" width="180px" label="手机号码">
        <template slot-scope="scope">
          <span>{{scope.row.phone}}</span>
        </template>
      </el-table-column>
      <!--<el-table-column align="center" label="登录ID">
        <template slot-scope="scope">
          <span>{{scope.row.openId}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="统一ID">
        <template slot-scope="scope">
          <span>{{scope.row.unionId}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="支付ID">
        <template slot-scope="scope">
          <span>{{scope.row.payId}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="左编号">
        <template slot-scope="scope">
          <span>{{scope.row.treeLeft}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="右编号">
        <template slot-scope="scope">
          <span>{{scope.row.treeRight}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="层次">
        <template slot-scope="scope">
          <span>{{scope.row.treeLevel}}</span>
        </template>
      </el-table-column>-->
      <el-table-column align="center" label="描述">
        <template slot-scope="scope">
          <span>{{scope.row.info}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="100px" label="上级ID">
        <template slot-scope="scope">
          <span>{{scope.row.parentId}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="100px" label="上级用户">
        <template slot-scope="scope">
          <span>{{scope.row.parentName}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="130px" label="状态">
        <<!--template slot-scope="scope">
          <span>{{scope.row.status}}</span>
        </template>-->
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status==0" >{{statusOptions[0]}}</el-tag>
          <el-tag v-if="scope.row.status==1" >{{statusOptions[1]}}</el-tag>
          <el-tag v-if="scope.row.status==2" >{{statusOptions[2]}}</el-tag>

        </template>
      </el-table-column>
      <el-table-column align="center" width="170px" label="加入时间">
        <template slot-scope="scope">
          <span>{{scope.row.joinTime}}</span>
        </template>
      </el-table-column>
      <!--<el-table-column align="center" label="升级时间">
        <template slot-scope="scope">
          <span>{{scope.row.levelTime}}</span>
        </template>
      </el-table-column>-->
      <el-table-column align="center" width="170px" label="登录时间">
        <template slot-scope="scope">
          <span>{{scope.row.loginTime}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="360px" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary"  v-if="canUpdate"  size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button  v-if="canSave"  size="mini" type="danger"
                      @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>

    </el-table>

    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit"
                     layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="70px"
               style='width: 400px; margin-left:50px;'>
        <el-form-item label="名字" prop="name">
          <el-input v-model="temp.name"></el-input>
        </el-form-item>
        <!--<el-form-item label="性别" prop="name">-->
          <!--<el-input v-model="temp.sex"></el-input>-->
        <!--</el-form-item>-->
        <el-form-item label="手机号码" prop="name">
          <el-input v-model="temp.phone"></el-input>
        </el-form-item>
        <!--<el-form-item label="登录ID" prop="name">-->
          <!--<el-input v-model="temp.openId"></el-input>-->
        <!--</el-form-item>-->
        <!--<el-form-item label="统一ID" prop="name">-->
          <!--<el-input v-model="temp.unionId"></el-input>-->
        <!--</el-form-item>-->
        <!--<el-form-item label="支付ID" prop="name">-->
          <!--<el-input v-model="temp.payId"></el-input>-->
        <!--</el-form-item>-->
        <!--<el-form-item label="左编号" prop="name">-->
          <!--<el-input v-model="temp.treeLeft"></el-input>-->
        <!--</el-form-item>-->
        <!--<el-form-item label="右编号" prop="name">-->
          <!--<el-input v-model="temp.treeRight"></el-input>-->
        <!--</el-form-item>-->
        <!--<el-form-item label="层次" prop="name">-->
          <!--<el-input v-model="temp.treeLevel"></el-input>-->
        <!--</el-form-item>-->
        <el-form-item label="描述" prop="name">
          <el-input v-model="temp.info"></el-input>
        </el-form-item>
        <el-form-item label="上级ID" prop="name">
          <el-input v-model="temp.parentId"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select class="filter-item" v-model="temp.status" placeholder="状态">
            <el-option v-for="(item,index) in  statusOptions" :key="item" :label="item"
                       :value="index">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="加入时间" prop="date">
          <el-date-picker v-model="temp.joinTime" type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss" placeholder="加入时间">
          </el-date-picker>
        </el-form-item>
        <!--<el-form-item label="升级时间" prop="date">-->
          <!--<el-date-picker v-model="temp.levelTime" type="datetime"-->
                          <!--value-format="yyyy-MM-dd HH:mm:ss" placeholder="升级时间">-->
          <!--</el-date-picker>-->
        <!--</el-form-item>-->
        <!--<el-form-item label="登录时间" prop="date">-->
          <!--<el-date-picker v-model="temp.loginTime" type="datetime"-->
                          <!--value-format="yyyy-MM-dd HH:mm:ss" placeholder="登录时间">-->
          <!--</el-date-picker>-->
        <!--</el-form-item>-->
        <el-form-item label="头像" prop="avatar">
          <el-upload
            ref="avatarUpload"
            action="http://upload.qiniup.com"
            :auto-upload="true"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :before-upload="handleUpload"
            :on-success="handleavatarUploadSuccess"
            :data="qData"
            :file-list="avatarList"
            :on-remove="handleavatarRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>

        <el-dialog :visible.sync="dialogVisible" append-to-body>
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialogForm">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确认</el-button>
        <el-button v-else type="primary" @click="updateData">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style type="stylus">
  .filter-container {
    padding-bottom: 20px;
  }
</style>

<script>
  import { getLists, save, update, remove } from '@/api/user'
  import waves from '@/directive/waves' // 水波纹指令
  import { parseTime } from '@/utils'

  import { getToken, domain } from '@/api/qiniu'
  import { listToStrs, strsToList } from '@/utils/imgUtil'

  import { mapGetters } from 'vuex'
  import { hasAuth } from '@/utils/auth'
  export default {
    name: 'test',
    directives: {
      waves
    },
    data() {
      return {
        tableKey: 0,
        list: null,
        total: null,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20,
          sidx: 'id',
          order: 'desc',
          name: null,
          sex: null,
          phone: null,
          openId: null,
          unionId: null,
          payId: null,
          treeLeft: null,
          treeRight: null,
          treeLevel: null,
          info: null,
          parentId: null,
          joinTime: null,
          levelTime: null,
          loginTime: null,
          status: null
        },
        statusOptions: ['整顿', '停用', '激活'],
        temp:
          {
            id: null, name: null, avatar: null, sex: null, phone: null, openId: null, unionId: null, payId: null, treeLeft: null, treeRight: null, treeLevel: null, info: null, parentId: null, joinTime: null, levelTime: null, loginTime: null, status: null },
        dialogFormVisible: false,
        dialogStatus:
          '',
        textMap:
          {
            update: '修改',
            create:
              '新增'
          },
        // 存在图片
        dialogImageUrl: '',
        dialogVisible:
          false,
        avatarList: [],
        rules:
          {
            name: [
              {
                required: false, message:
                  '必填字段', trigger:
                  'change'
              }
            ],
            avatar: [
              {
                required: false, message:
                  '必填字段', trigger:
                  'change'
              }
            ],
            sex: [
              {
                required: false, message:
                  '必填字段', trigger:
                  'change'
              }
            ],
            phone: [
              {
                required: false, message:
                  '必填字段', trigger:
                  'change'
              }
            ],
            openId: [
              {
                required: false, message:
                  '必填字段', trigger:
                  'change'
              }
            ],
            unionId: [
              {
                required: false, message:
                  '必填字段', trigger:
                  'change'
              }
            ],
            payId: [
              {
                required: false, message:
                  '必填字段', trigger:
                  'change'
              }
            ],
            treeLeft: [
              {
                required: false, message:
                  '必填字段', trigger:
                  'change'
              }
            ],
            treeRight: [
              {
                required: false, message:
                  '必填字段', trigger:
                  'change'
              }
            ],
            treeLevel: [
              {
                required: false, message:
                  '必填字段', trigger:
                  'change'
              }
            ],
            info: [
              {
                required: false, message:
                  '必填字段', trigger:
                  'change'
              }
            ],
            parentId: [
              {
                required: false, message:
                  '必填字段', trigger:
                  'change'
              }
            ],
            joinTime: [
              {
                required: false, message:
                  '必填字段', trigger:
                  'change'
              }
            ],
            levelTime: [
              {
                required: false, message:
                  '必填字段', trigger:
                  'change'
              }
            ],
            loginTime: [
              {
                required: false, message:
                  '必填字段', trigger:
                  'change'
              }
            ],
            status: [
              {
                required: false, message:
                  '必填字段', trigger:
                  'blur'
              }
            ]
          },
        downloadLoading: false,
        qData:
          {
            token: '',
            key:
              ''
          }
      }
    },
    created() {
      this.getList()
    },
    computed: {
      ...mapGetters([
        'perms'
      ]),
      canSave() {
        return hasAuth(this.perms, 'user:save')
      },
      canDelete() {
        return hasAuth(this.perms, 'user:delete')
      },
      canUpdate() {
        return hasAuth(this.perms, 'user:update')
      },
      canList() {
        return hasAuth(this.perms, 'user:list')
      }
    },
    methods: {
      getList() {
        this.listLoading = true
        // // 如果存在时间
        // if (this.listQuery.joinTime) {
        //   this.listQuery['joinTimeStart'] = parseTime(this.listQuery.joinTime[0])
        //   this.listQuery['joinTimeEnd'] = parseTime(this.listQuery.joinTime[1])
        // } else {
        //   this.listQuery['joinTimeStart'] = null
        //   this.listQuery['joinTimeEnd'] = null
        // }
        // // 如果存在时间
        // if (this.listQuery.levelTime) {
        //   this.listQuery['levelTimeStart'] = parseTime(this.listQuery.levelTime[0])
        //   this.listQuery['levelTimeEnd'] = parseTime(this.listQuery.levelTime[1])
        // } else {
        //   this.listQuery['levelTimeStart'] = null
        //   this.listQuery['levelTimeEnd'] = null
        // }
        // // 如果存在时间
        // if (this.listQuery.loginTime) {
        //   this.listQuery['loginTimeStart'] = parseTime(this.listQuery.loginTime[0])
        //   this.listQuery['loginTimeEnd'] = parseTime(this.listQuery.loginTime[1])
        // } else {
        //   this.listQuery['loginTimeStart'] = null
        //   this.listQuery['loginTimeEnd'] = null
        // }
        getLists(this.listQuery).then(response => {
          this.list = response.data.list
          this.total = response.data.total
          this.listLoading = false
        })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      handleSizeChange(val) {
        this.listQuery.limit = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.listQuery.page = val
        this.getList()
      },
      handleModifyStatus(row, status) {
        this.$message({
          message: '操作成功',
          type: 'success'
        })
        row.status = status
      },
      beforeFormShow(row) {
        this.resetTemp(row) // 更新数据
        // 存在图片
        this.initQiniu()

        // 存在图片字段转换图片地址显示
        this.initImgUrl()
      },
      afterFormShow(row) {

      },
      beforeFormCommit() {
        this.initImgName()// 图片转换
      },
      resetTemp(row) {
        this.temp = {}
        if (row) {
          this.temp = Object.assign({}, row) // copy obj
        }
      },
      handleCreate() {
        this.beforeFormShow()
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.afterFormShow()
          this.$refs['dataForm'].clearValidate()
        })
      },
      handleDelete(row) {
        this.beforeFormShow(row)
        this.temp = Object.assign({}, row) // copy obj
        this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // this.$message({
          //   type: 'success',
          //   message: '删除成功!'
          // })
          this.deleteData()
        })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
      },
      // 显示将图片名封装成可以展示状态集合
      initImgUrl() {
        this.avatarList = strsToList(this.temp.avatar, domain)
      },
      // 关闭显示窗口 重置图片地址 防止错乱
      resetImgUrl() {
        this.avatarList = []
      },
      // 上传或者更新的时候从图片链接中获取图片名字
      initImgName() {
        this.temp.avatar = listToStrs(this.avatarList)
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.beforeFormCommit()
            save(this.temp).then(res => {
              this.temp = res.data
              this.list.unshift(this.temp)
              this.closeDialogForm()
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        }
        )
      },
      deleteData() {
        const ids = [this.temp.id]
        remove(ids).then(res => {
          // 从当前队列中移除
          for (const v of this.list
          ) {
            if (v.id === this.temp.id) {
              const index = this.list.indexOf(v)
              this.list.splice(index, 1)
              break
            }
          }
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
        })
      },
      handleUpdate(row) {
        this.beforeFormShow(row)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.beforeFormCommit()
            update(this.temp).then(() => {
              for (const v of this.list
              ) {
                if (v.id === this.temp.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.temp)
                  break
                }
              }
              this.closeDialogForm()
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        }
        )
      },
      closeDialogForm() {
        // 存在图片
        this.resetImgUrl()
        this.dialogFormVisible = false
      },
      handleDownload() {
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = [
            '序号',
            '名字',
            '性别',
            '手机号码',
            '登录ID',
            '统一ID',
            '支付ID',
            '左编号',
            '右编号',
            '层次',
            '描述',
            '上级ID',
            '状态',
            '加入时间',
            '升级时间',
            '登录时间'
          ]
          const filterVal = ['id',
            'name',
            'sex',
            'phone',
            'openId',
            'unionId',
            'payId',
            'treeLeft',
            'treeRight',
            'treeLevel',
            'info',
            'parentId',
            'status',
            'joinTime',
            'levelTime',
            'loginTime'
          ]
          const data = this.formatJson(filterVal, this.list)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: 'table-list'
          })
          this.downloadLoading = false
        })
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => {
          return v[j]
        }
        ))
      },
      // 存在图片
      handleUpload(file) {
        this.qData.key = new Date().valueOf() + file.name
      },
      initQiniu() {
        // 获取七牛配置
        getToken().then(res => {
          this.qData.token = res.data
        })
          .catch(error => {
            console.log(error)
          })
      },
      handleavatarUploadSuccess(response, file, fileList) {
        this.avatarList.push({ name: file.response.key, url: domain + file.response.key })
      },
      handleavatarRemove(file, fileList) {
        for (var fn of this.avatarList) {
          if (fn.name === file.name) {
            this.avatarList.splice(this.avatarList.indexOf(fn), 1)
          }
        }
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      }
    }
  }
</script>
